<?php

namespace api\modules\v1\controllers;

use common\helpers\ResultHelper;
use common\models\cargo\Cargo;
use common\models\cargo\Order;
use common\models\owner\Owner;
use Yii;
use api\controllers\OnAuthController;
use common\enums\StatusEnum;
use common\components\Wechat;
use Yansongda\Pay\Pay;
use yii\web\Response;

//use Yansongda\Pay\Log;
require (dirname(__FILE__).'/../../../../vendor/pay/src/Pay.php');
require (dirname(__FILE__).'/../../../../vendor/pay/src/Support/Config.php');
require (dirname(__FILE__).'/../../../../vendor/pay/src/Exceptions/InvalidArgumentException.php');
require (dirname(__FILE__).'/../../../../vendor/pay/src/Gateways/Wechat/MiniappGateway.php');


class WechatController extends OnAuthController
{
    public $modelClass = '';

    /**
     * 微信相关接口
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['getopenid','setorder','wechat','notify','getuser'];
    //配置参数
    protected $config = [
        'wechat' => [
            'miniapp_id' => 'wx28ace6ca288c53d1',//微信小程序id
            'mch_id' => '1603929953',//商户号
            'key' => '051d47c87619e3dbfb7bd915faed3ff1',//32位秘钥
            'notify_url' => 'https://logistics.xiaoliang666.top/api/v1/wechat/notify',//回调链接地址
        ],
    ];
    /**
     * @return array
     * 获取open_id
     * /api/v1/wechat/getopenid
     */
    public function actionGetopenid(){
        $code = Yii::$app->request->get('code');
        $appid = 'wx28ace6ca288c53d1';            //微信小程序id
        $appsecret = 'e43b8fb11316c82c3009548b007e5f47';        //小程序秘钥
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";//请求的微信接口
        $str = file_get_contents($url);
        $json = json_decode($str);
        $arr = get_object_vars($json);
        return $arr;
    }
    /**
     * 创建订单
     * /api/v1/wechat/setorder
     */
    public function actionSetorder()
    {
        $get = Yii::$app->request->get();
        if(!$get){
            return ResultHelper::json(400,'缺少参数');
        }
        $arr = rand(100000,999999);
        $get['out_trade_no'] = time().$arr;
        $order = new Order();
        $order ->attributes = $get;
        $order ->status = 1;
        $order ->state = 1;
        $data = $order->save();
        if(!$data){
            return ['code'=>500,'msg'=>'操作失败：'.$order::getModelError($order)];
        }
        return $order;
    }
    /**
     * /api/v1/wechat/wechat
     * 微信统一下单
     */
    public function actionWechat()
    {
        $post =  Yii::$app->request->post();
        $config_biz = [
            'out_trade_no' =>  $post['out_trade_no'],
            'total_fee' => 1, // **单位：分**
            'openid' =>  $post['open_id'],
            'body' =>  $post['body'],
        ];
        $pay = new Pay($this->config);
        $data = $pay->driver('wechat')->gateway('miniapp')->pay($config_biz);
        return $data;
    }
     /**
     * 支付成功之后回调接口
     * /api/v1/wechat/notify
     */
    public function actionNotify()
    { 
          $post = file_get_contents("php://input");//接受流
//           file_put_contents('/www/aa.txt',$post);
//           $post = '<xml><appid><![CDATA[wx28ace6ca288c53d1]]></appid>
//<bank_type><![CDATA[OTHERS]]></bank_type>
//<cash_fee><![CDATA[1]]></cash_fee>
//<fee_type><![CDATA[CNY]]></fee_type>
//<is_subscribe><![CDATA[N]]></is_subscribe>
//<mch_id><![CDATA[1603929953]]></mch_id>
//<nonce_str><![CDATA[NVf2Fvr44GHFwwrh]]></nonce_str>
//<openid><![CDATA[o-Iku5N6JB1Yn_BeK0wObpA_Fngw]]></openid>
//<out_trade_no><![CDATA[1605145536768282]]></out_trade_no>
//<result_code><![CDATA[SUCCESS]]></result_code>
//<return_code><![CDATA[SUCCESS]]></return_code>
//<sign><![CDATA[308076B33E14B17880181D2875F79157]]></sign>
//<time_end><![CDATA[20201112094610]]></time_end>
//<total_fee>1</total_fee>
//<trade_type><![CDATA[JSAPI]]></trade_type>
//<transaction_id><![CDATA[4200000848202011120684113108]]></transaction_id>
//</xml>';

        $pay = new Pay($this->config);
        $data = $pay->driver('wechat')->gateway('miniapp')->verify($post);
        $state = Order::find()->where(['out_trade_no'=>$data['out_trade_no']])->select('state')->asArray()->one();//查询订单号的状态
        if($state['state']==2){//订单号状态如果支付成功
            return ResultHelper::json(400,'该订单已经执行过了');
        }
        $info = Cargo::find()->where(['open_id'=>$data['openid']])->select('vip')->one();//查询vip到期日期
        if($info['vip']>=date('Y-m-d H:i')){
            $info['vip'] = date("Y-m-d H:i", strtotime("+1 year", strtotime($info['vip'])));//续费情况
        }else{
            $info['vip'] =date('Y-m-d H:i', strtotime("+1 year"));//之前没有充值过
        }
        //修改货主会员到期时间
        $cargo = Yii::$app->db->createCommand()->update('rf_wl_cargo', ['vip' => $info['vip'] ], ['open_id'=>$data['openid']])->execute();
        if(!$cargo){
            return ResultHelper::json(400,'请求失败');
        }
        //修改订单状态，上传微信订单
        $arr = Yii::$app->db->createCommand()->update('rf_wl_order', ['state' =>2,'transaction_id'=>$data['transaction_id']], ['out_trade_no'=>$data['out_trade_no']])->execute();
        echo '<xml>
 <return_code><![CDATA[SUCCESS]]></return_code> 
 <return_msg><![CDATA[OK]]></return_msg> 
</xml>';die;
    }

    /**
     * /api/v1/wechat/getuser
     * 判断用户身份
     */
    public function actionGetuser()
    {
        $get = Yii::$app->request->get();
        if(!$get['open_id']){
            return ResultHelper::json(400,'缺少参数');
        }
        $cargo = Cargo::find()->select('id,name')->where(['open_id'=>$get['open_id']])->asArray()->one();
        if($cargo){
            return ResultHelper::json(201,'用户为货主',$cargo);
        }
        $owner = Owner::find()->select('id,name')->where(['open_id'=>$get['open_id']])->asArray()->one();
        if($owner){
            return ResultHelper::json(200,'用户为车主',$owner);
        }
        return ResultHelper::json(500,'获取失败');
    }
}

